/*
 * pcimem.c: Simple program to read/write from/to a pci device from userspace.
 *
 *  Copyright (C) 2010, Bill Farrow (bfarrow@beyondelectronics.us)
 *
 *  Based on the devmem2.c code
 *  Copyright (C) 2000, Jan-Derk Bakker (J.D.Bakker@its.tudelft.nl)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <stdarg.h>
#include <memory.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/poll.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <pthread.h>
#include <math.h>
#include <termios.h>
#include <netinet/in.h>

#include "appcmd.h"


#define FP_DEV_1 "/sys/bus/pci/devices/0000:01:00.0/resource0"
#define FP_DEV_2 "/sys/bus/pci/devices/0000:01:00.0/resource1"
#define FP_DEV_3 "/sys/bus/pci/devices/0000:01:00.0/resource2"

#define PRINT_ERROR \
	do { \
		fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", \
		__LINE__, __FILE__, errno, strerror(errno)); exit(1); \
	} while(0)

static int global_fd0 = -1;
static int global_fd1 = -1;
static int global_fd2 = -1;

extern int Xil_In32(uint64_t phyaddr);
extern void Xil_Out32(uint64_t phyaddr, uint32_t val);

void SetGpioReg(unsigned int addrBase,unsigned int addrOffset,unsigned int value)
{
	Xil_Out32(addrBase+addrOffset, value);
}

int GetGpioReg(unsigned int addrBase,unsigned int addrOffset)
{
	int ans=0;
	ans=Xil_In32(addrBase+addrOffset);
	return ans;
}

void SetPcieMemReg(unsigned int region,unsigned int addrOffset,unsigned int value)
{
	unsigned int addrBase=0;
	if(region==0)
	{
		addrBase=0xa0000000;
	}
	else if(region==1)
	{
		addrBase=0xa1000000;
	}
	else if(region==2)
	{
		addrBase=0xa1010000;
	}
	else
	{
		addrBase=0xa0000000;
	}
	Xil_Out32(addrBase+addrOffset, value);
}

int GetPcieMemReg(unsigned int region,unsigned int addrOffset)
{
	int ans=0;
	unsigned int addrBase=0;
	if(region==0)
	{
		addrBase=0xa0000000;
	}
	else if(region==1)
	{
		addrBase=0xa1000000;
	}
	else if(region==2)
	{
		addrBase=0xa1010000;
	}
	else
	{
		addrBase=0xa0000000;
	}
	ans=Xil_In32(addrBase+addrOffset);
	return ans;
}

unsigned int regtoul(const char *str)
{
	int cbase = 10;
	if(str[0]=='0'&&(str[1]=='x'||str[1]=='X')) {
		cbase = 16;
	}
	return strtoul(str, NULL, cbase);
}

int fd_initial(int num)
{

	int fd = -1;

	/*
		Open modem device for reading and writing and not as controlling tty
		because we don't want to get killed if linenoise sends CTRL-C.
	*/
	if(num==0)
	{
		printf("Open '%s' .. ", FP_DEV_1);
		fd = open(FP_DEV_1, O_RDWR | O_SYNC );
	}
	else if(num==1)
	{
		printf("Open '%s' .. ", FP_DEV_2);
		fd = open(FP_DEV_2, O_RDWR | O_SYNC );
	}
	else if(num==2)
	{
		printf("Open '%s' .. ", FP_DEV_3);
		fd = open(FP_DEV_3, O_RDWR | O_SYNC );
	}
	else
	{
		printf("Open error.\n");
		return -1;
	}
	if (fd <0) {
		printf("failed (err = %d)\n", fd);
		return -1;
	}

	printf("Done\n");
	return fd;
}

int fd_exit(int fd,int num)
{
	if(num==0)
	{
		printf("Close '%s' .. ", FP_DEV_1);
	}
	else if(num==1)
	{
		printf("Close '%s' .. ", FP_DEV_2);
	}
	else
	{
		printf("Close '%s' .. ", FP_DEV_3);
	}
	close(fd);

	printf("Done\n");

	return 0;
}

/*---------------------------------------------------------------------------------------------------------------------------------------------------
 * help
 */
APPCMD_OPTION_FUNCTION(help)
{
	int optn;
	appcmd_options_t *poption, *opt_list = (appcmd_options_t *)p;

	printf("\n** SDI PCIE Test Samples, Version: 1.0.1\n");
	printf("\tCopyright (c) 2019 CETC Co., Ltd.\n");
	printf("\tRegion0(a0000000-a0ffffff) 16MB.\n");
	printf("\tRegion1(a1000000-a100ffff) 64KB.\n");
	printf("\tRegion2(a1010000-a101ffff) 64KB.\n");
	printf("\n** commands:\n");
	for( optn=0; (poption=&opt_list[optn]) && poption->name; optn++) {
		printf("\t%-10s\t: %s\n", poption->name, poption->help);
	};
	return 0;
}

/*---------------------------------------------------------------------------------------------------------------------------------------------------
 * console
 */

APPCMD_OPTION_FUNCTION(set)
{
	unsigned int region,offset, value;

	if(argc < 3) {
		printf("Invalid command line for 'set'\n");
		return -1;
	}
	region = regtoul(argv[1]);
	offset = regtoul(argv[2]);
	value = regtoul(argv[3]);

	printf("Set value 0x%x to region 0x%x offset 0x%x .. \n", value, region,offset);

	SetPcieMemReg(region,offset, value);

	printf("done \n");

	return 0;
}

APPCMD_OPTION_FUNCTION(get)
{
	unsigned int region,offset, value;

	if(argc < 2) {
		printf("Invalid command line for 'set'\n");
		return -1;
	}

	region = regtoul(argv[1]);
	offset = regtoul(argv[2]);

	printf("Get value from region 0x%x offset 0x%x .. \n", region,offset);

	value = GetPcieMemReg(region,offset);

	printf("Return value of region 0x%x offset 0x%x : 0x%x \n", region,offset, value);

	return 0;
}

#define QUIT_MARK_RETURN	0xdeadbeef

APPCMD_OPTION_FUNCTION(quit)
{
	return QUIT_MARK_RETURN;
}

static appcmd_options_t cmdlist_console[]=
{
	APPCMD_OPTION(set,		"Set register value:\n"
							"\t\t\tset <region> <offset> <value>"
							, NULL),
	APPCMD_OPTION(get,		"Get register value:\n"
							"\t\t\tget <region> <offset>"
							, NULL),
	APPCMD_OPTION(help,		"Help for commands", cmdlist_console),
	APPCMD_OPTION(quit,		"Quit from console", NULL),
	APPCMD_OPTION_NULL,
};

APPCMD_OPTION_FUNCTION(console)
{
	int strl;
	char *str=NULL;
	size_t n=0;
	while(1) {
		printf("\nsdi pcie test> ");
		strl = getline(&str, &n, stdin);
		if(strl <= 0)
			continue;
		if (0==strncmp(str, "quit", 4))
			break;
		appcmd_options_runcmd(cmdlist_console, str);
	};
	if(str)
		free(str);
	return 0;
}

/*---------------------------------------------------------------------------------------------------------------------------------------------------
 * main
 */
static appcmd_options_t cmdlist[]=
{
	APPCMD_OPTION(console,	"Start console for env operation", NULL),
	APPCMD_OPTION(help,		"Show help infomation", cmdlist),
	APPCMD_OPTION_NULL,
};

static char commands[512] = {0,};


int main(int argc, char *argv[])
{
	int argi;
	int data;

	printf("Linux SDI_PCIE_Test APP start(Version 0.1)\r\n");
	SetGpioReg(0x90000000,0x100004,0x100007);
	data=GetGpioReg(0x90000000,0x100004);
	printf("sdi pcie control reg is 0x%x\n",data);

	if (argc<2) {
		strcpy(commands, "console");
	} else {
		char *str = commands;
		for (argi=1; argi<argc; argi++) {
			int pn = snprintf(str, (commands+sizeof(commands)-4-str), "%s  ", argv[argi]);
			if (pn<=0) break;
			str+= pn;
		}
	}

	global_fd0 = fd_initial(0);
	global_fd1 = fd_initial(1);
	global_fd2 = fd_initial(2);

	if ((global_fd0<0)||(global_fd1<0)||(global_fd2<0)) {
		printf("\n Invalid sdi region! \n");
		return -1;
	}

	appcmd_options_runcmd(cmdlist, commands);

	fd_exit(global_fd0,0);
	fd_exit(global_fd1,1);
	fd_exit(global_fd2,2);
	return 0;
}
